// src/store/auth.js
import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || null,
    role: localStorage.getItem('user_type') || null,
    userId: localStorage.getItem('user_id') || null
  }),
  actions: {
    // 修改方法名为setLoginData保持一致性
    setLoginData({ token, role, userId }) {
      this.token = token
      this.role = role
      this.userId = userId
      localStorage.setItem('token', token)
      localStorage.setItem('user_type', role)
      localStorage.setItem('user_id', userId)
    },
    loadFromLocalStorage() {
      // 从 localStorage 获取数据，并更新 store
      const token = localStorage.getItem('token');
      const role = localStorage.getItem('user_type');
      const userId = localStorage.getItem('user_id');

      if (token && role && userId) {
        this.setLoginData({
          token,
          role,
          userId,
        });
      }
    },
    logout() {
      // 清除状态
      this.token = null
      this.role = null
      this.userId = null
      
      // 清除localStorage
      localStorage.removeItem('token')
      localStorage.removeItem('user_type')
      localStorage.removeItem('user_id')
      
      // 清除其他可能存在的用户相关数据
      sessionStorage.clear()
      
      // 发布自定义事件，通知应用其他部分用户已登出
      window.dispatchEvent(new CustomEvent('user-logout'))
      
      console.log('用户已成功登出，所有状态已重置')
    }
  },
  getters: {
    isAdmin: (state) => state.role === 'admin',
    isLoggedIn: (state) => !!state.token
  }
})